<template>
  <view class="container">
          <!-- 顶部选项卡 -->
          <view class="category-tabs">
              <u-tabs :list="list1" @click="clickTab" lineColor="#47d2d9"
                  :activeStyle="{color: '#31cbd9', fontWeight: 'bold', transform: 'scale(1.05)'}" 
                  :inactiveStyle="{color: '#666'}"
                  :current="currentTabIndex"
                  itemStyle="padding: 0 20rpx; height: 80rpx;"></u-tabs>
          </view>
  
          <!-- 订单列表 -->
          <view class="order-list" v-if="currentOrders.length > 0">
              <view class="order-item" v-for="(order, index) in currentOrders" :key="index">
                  <!-- 订单头部 -->
                  <view class="order-header">
                      <text class="order-sn">订单编号: {{ order.ordersn }}</text>
  <!--                    <text class="order-status" :style="{color: getStatusColor(order.state)}">{{ getStatusText(order.state) }}</text> -->
                  </view>
  
                  <!-- 商品列表 -->
                  <view class="order-products" v-for="(product, pIndex) in order.products" :key="pIndex" @click="toDetail(product)">
                      <image class="product-image" :src="baseUrl + '/' + product.goodsimg" mode="aspectFill"
                          ></image>
                      <view class="product-info">
                          <text class="product-name">{{ product.goodsname }}</text>
                          <view class="product-meta">
                              <text class="product-price">¥{{ product.price }}</text>
                              <text class="product-quantity">x{{ product.quartity }}</text>
                          </view>
                          <text class="product-spec" v-if="product.spec">规格: {{product.spec}}</text>
                      </view>
                  </view>
  
                  <!-- 订单底部 -->
                  <view class="order-footer">
                      <view class="order-total-wrap">
                          <text class="order-total-label">共{{order.products.length}}件商品 合计:</text>
                          <text class="order-total">¥{{ getOrderTotal(order.products) }}</text>
                      </view>
                      <view class="order-actions">
                          <button class="btn-action" v-if="order.state === 0" @click.stop="handlePay(order)">去支付</button>
                          <button class="btn-action" v-if="order.state === 1">提醒发货</button>
  						<button class="btn-action btn-gray" v-if="order.state === 1">申请售后</button>
                          <button class="btn-action" v-if="order.state === 2" @click.stop="handleConfirm(order)">确认收货</button>
  						<button class="btn-action btn-gray" v-if="order.state === 2">申请售后</button>
                          <button class="btn-action" v-if="order.state === 3">再次购买</button>
                          <button class="btn-action btn-gray" v-if="order.state === 3">申请售后</button>
                      </view>
                  </view>
              </view>
              
              <!-- 加载更多 -->
              <view class="load-more" v-if="hasMore" @click="loadMoreData">
                  <u-loadmore :status="loadingMore ? 'loading' : 'loadmore'" 
                      :loadText="{
                          loadmore: '上拉加载更多',
                          loading: '正在加载...'
                      }" 
                      color="#ccc" />
              </view>
              <view class="no-more" v-else>
                  <u-line color="#eee" length="60%"></u-line>
                  <text class="no-more-text">没有更多了</text>
                  <u-line color="#eee" length="60%"></u-line>
              </view>
          </view>
  
          <!-- 空状态 -->
          <view class="empty-list" v-else>
              <text class="empty-text">{{ loading ? '加载中...' : '暂无订单数据' }}</text>
              <button class="btn-shopping" v-if="!loading" @click="goToHome">去逛逛</button>
          </view>
      </view>
</template>

<script>
import { API_BASE_URL } from '../../utils/appConfig'
import { 
  getOrderByuserId, 
  getOrderByuserIdAndState, 
  getOrderDetailByOrdersn 
} from '@/api/order.js'

export default {
  data() {
    return {
      list1: [
        { name: '全部', state: null },
        { name: '待付款', state: 0 },
        { name: '待发货', state: 1 },
        { name: '已发货', state: 2 },
        { name: '已完成', state: 3 },
        { name: '售后', state: 4 }
      ],
      allOrders: [],
      currentOrders: [],
      currentTabIndex: 0,
      loading: false,
      baseUrl: API_BASE_URL,
      pageSize: 10, // 每页显示数量
      currentPage: 1, // 当前页码
      loadingMore: false, // 是否正在加载更多
      hasMore: false, // 是否还有更多数据
      currentState: null // 当前筛选状态
    }
  },
  onLoad() {
    this.loadAllOrders()
  },
  methods: {
    // 加载所有订单
    async loadAllOrders() {
      this.loading = true
      this.currentPage = 1
      try {
        const response = await getOrderByuserId(this.currentPage, this.pageSize)
        console.log('订单列表响应:', response)
        
        if (response.code === 200) {
          // 处理可能的响应数据结构差异
          const orders = response.data?.list || response.data || []
          const total = response.data?.total || 0
          
          this.hasMore = orders.length < total
          
          if (orders && orders.length > 0) {
            // 并行获取所有订单详情
            const ordersWithDetails = await Promise.all(
              orders.map(async order => {
                try {
                  const detailRes = await getOrderDetailByOrdersn(order.ordersn)
                  console.log(`订单${order.ordersn}详情:`, detailRes)
                  
                  // 处理可能的详情数据结构差异
                  const products = detailRes.code === 200 ? 
                    (detailRes.data?.list || detailRes.data || []) : []
                  
                  return {
                    ...order,
                    products: Array.isArray(products) ? products : [products]
                  }
                } catch (error) {
                  console.error(`获取订单${order.ordersn}详情失败:`, error)
                  return {
                    ...order,
                    products: []
                  }
                }
              })
            )
            
            this.allOrders = ordersWithDetails.filter(order => order) // 过滤掉可能的空值
            this.currentOrders = [...this.allOrders]
            this.currentState = null
          } else {
            this.allOrders = []
            this.currentOrders = []
          }
        } else {
          this.allOrders = []
          this.currentOrders = []
        }
      } catch (error) {
        console.error('获取订单失败:', error)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
        this.allOrders = []
        this.currentOrders = []
      } finally {
        this.loading = false
      }
    },
    
    // 按状态加载订单
    async loadOrdersByState(state) {
      this.loading = true
      this.currentPage = 1
      this.currentState = state
      
      try {
        if (state === null) {
          await this.loadAllOrders()
          return
        }
        
        const response = await getOrderByuserIdAndState(state, this.currentPage, this.pageSize)
        console.log(`状态${state}订单响应:`, response)
        
        if (response.code === 200) {
          // 处理可能的响应数据结构差异
          const orders = response.data?.list || response.data || []
          const total = response.data?.total || 0
          
          this.hasMore = orders.length < total
          
          if (orders && orders.length > 0) {
            const ordersWithDetails = await Promise.all(
              orders.map(async order => {
                try {
                  const detailRes = await getOrderDetailByOrdersn(order.ordersn)
                  console.log(`订单${order.ordersn}详情:`, detailRes)
                  
                  // 处理可能的详情数据结构差异
                  const products = detailRes.code === 200 ? 
                    (detailRes.data?.list || detailRes.data || []) : []
                  
                  return {
                    ...order,
                    products: Array.isArray(products) ? products : [products]
                  }
                } catch (error) {
                  console.error(`获取订单${order.ordersn}详情失败:`, error)
                  return {
                    ...order,
                    products: []
                  }
                }
              })
            )
            
            this.currentOrders = ordersWithDetails.filter(order => order) // 过滤掉可能的空值
          } else {
            this.currentOrders = []
          }
        } else {
          this.currentOrders = []
        }
      } catch (error) {
        console.error(`获取状态${state}订单失败:`, error)
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
        this.currentOrders = []
      } finally {
        this.loading = false
      }
    },
    
    // 加载更多数据
    async loadMoreData() {
      if (this.loadingMore || !this.hasMore) return
      
      this.loadingMore = true
      this.currentPage++
      
      try {
        let response
        
        if (this.currentState === null) {
          // 加载全部订单的更多数据
          response = await getOrderByuserId(this.currentPage, this.pageSize)
        } else {
          // 加载特定状态订单的更多数据
          response = await getOrderByuserIdAndState(this.currentState, this.currentPage, this.pageSize)
        }
        
        console.log(`加载更多订单响应:`, response)
        
        if (response.code === 200) {
          const orders = response.data?.list || response.data || []
          const total = response.data?.total || 0
          
          this.hasMore = orders.length < total
          
          if (orders && orders.length > 0) {
            const ordersWithDetails = await Promise.all(
              orders.map(async order => {
                try {
                  const detailRes = await getOrderDetailByOrdersn(order.ordersn)
                  console.log(`订单${order.ordersn}详情:`, detailRes)
                  
                  const products = detailRes.code === 200 ? 
                    (detailRes.data?.list || detailRes.data || []) : []
                  
                  return {
                    ...order,
                    products: Array.isArray(products) ? products : [products]
                  }
                } catch (error) {
                  console.error(`获取订单${order.ordersn}详情失败:`, error)
                  return {
                    ...order,
                    products: []
                  }
                }
              })
            )
            
            // 将新数据添加到当前订单列表
            this.currentOrders = [...this.currentOrders, ...ordersWithDetails.filter(order => order)]
            
            // 如果是加载全部订单，也更新全部订单数据
            if (this.currentState === null) {
              this.allOrders = [...this.allOrders, ...ordersWithDetails.filter(order => order)]
            }
          }
        }
      } catch (error) {
        console.error('加载更多订单失败:', error)
        uni.showToast({
          title: '加载更多失败',
          icon: 'none'
        })
        this.currentPage-- // 加载失败回退页码
      } finally {
        this.loadingMore = false
      }
    },
    
    // 标签点击事件
    clickTab(e) {
      this.currentTabIndex = e.index
      const selectedState = this.list1[e.index].state
      this.loadOrdersByState(selectedState)
    },
    
    // 获取状态文本
    getStatusText(state) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '已发货',
        3: '已完成',
        4: '售后'
      }
      return statusMap[state] || '未知状态'
    },
    
    // // 获取状态颜色
    // getStatusColor(state) {
    //   const colorMap = {
    //     0: '#ff4d4f', // 红色
    //     1: '#faad14', // 橙色
    //     2: '#1890ff', // 蓝色
    //     3: '#52c41a', // 绿色
    //     4: '#722ed1'  // 紫色
    //   }
    //   return colorMap[state] || '#999'
    // },
    
    // 计算订单总价
    getOrderTotal(products) {
      if (!products || !products.length) return '0.00'
      const total = products.reduce((sum, product) => {
        const price = Number(product.price) || 0
        const quantity = Number(product.quartity) || 1
        return sum + (price * quantity)
      }, 0)
      return total.toFixed(2)
    },
    
    // 支付按钮处理
    handlePay(order) {
      uni.showLoading({ title: '支付处理中...' })
      console.log('支付订单:', order)
      setTimeout(() => {
        uni.hideLoading()
        uni.showToast({ title: '支付成功', icon: 'success' })
        // 重新加载待付款订单
        this.loadOrdersByState(0)
      }, 1500)
    },
    
    // 确认收货按钮处理
    handleConfirm(order) {
      uni.showModal({
        title: '确认收货',
        content: '确认您已收到商品？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '处理中...' })
            try {
              // 这里应该调用确认收货的API
              // 模拟API调用成功
              await new Promise(resolve => setTimeout(resolve, 1000))
              
              uni.hideLoading()
              uni.showToast({ title: '确认收货成功', icon: 'success' })
              
              // 更新订单状态
              const index = this.currentOrders.findIndex(o => o.ordersn === order.ordersn)
              if (index !== -1) {
                this.currentOrders[index].state = 3 // 更新为已完成状态
              }
              
              // 如果当前筛选的是已发货状态，重新加载数据
              if (this.currentState === 2) {
                this.loadOrdersByState(2)
              }
            } catch (error) {
              uni.hideLoading()
              uni.showToast({ title: '确认收货失败', icon: 'none' })
            }
          }
        }
      })
    },
    
    toDetail(product) {
      uni.navigateTo({
        url: `/pages/message/index?id=${product.goodsid}`
      });
    },
    
    goToHome() {
      uni.switchTab({
        url: '/pages/home/index'
      })
    },
    
    // 图片加载失败处理
   
  }
}
</script>


<style scoped lang="scss">
    .container {
        padding: 0;
        background-color: #f7f7f7;
        min-height: 100vh;
    }

    /* 选项卡样式 */
    .category-tabs {
        position: sticky;
        top: 0;
        z-index: 10;
        background-color: #fff;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
    }

    /* 订单列表 */
    .order-list {
        padding: 0 24rpx;
    }

    /* 订单项 */
    .order-item {
        margin: 24rpx 0;
        padding: 24rpx;
        background-color: #fff;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    }

    /* 订单头部 */
    .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 20rpx;
        border-bottom: 1rpx solid #f5f5f5;
        margin-bottom: 20rpx;
    }

    .order-sn {
        color: #666;
        font-size: 18rpx;
    }

    .order-status {
        font-size: 20rpx;
        font-weight: bold;
    }

    /* 商品项 */
    .order-products {
        display: flex;
        align-items: center;
        margin-bottom: 24rpx;
        padding: 16rpx;
        background-color: #fafafa;
        border-radius: 12rpx;
        transition: all 0.2s;
        
        &:active {
            background-color: #f5f5f5;
            transform: scale(0.99);
        }
    }

    .product-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 12rpx;
        margin-right: 24rpx;
        background-color: #f5f5f5;
    }

    .product-info {
        flex: 1;
        display: flex;
        flex-direction: column;
    }

    .product-name {
        font-size: 28rpx;
        color: #333;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-bottom: 12rpx;
    }

    .product-meta {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;
    }

    .product-price {
        font-size: 30rpx;
        color: #ff4d4f;
        font-weight: bold;
        margin-right: 16rpx;
    }

    .product-quantity {
        font-size: 26rpx;
        color: #999;
    }

    .product-spec {
        font-size: 24rpx;
        color: #999;
        padding: 4rpx 8rpx;
        background-color: #f5f5f5;
        border-radius: 4rpx;
        align-self: flex-start;
    }

    /* 订单底部 */
    .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 20rpx;
        border-top: 1rpx solid #f5f5f5;
    }

    .order-total-wrap {
        display: flex;
        align-items: baseline;
    }

    .order-total-label {
        font-size: 26rpx;
        color: #666;
        margin-right: 8rpx;
    }

    .order-total {
        font-size: 32rpx;
        color: #ff4d4f;
        font-weight: bold;
    }

    .order-actions {
        display: flex;
        justify-content: flex-end;
    }

    .btn-action {
        margin-left: 16rpx;
        padding: 0 28rpx;
        height: 56rpx;
        line-height: 56rpx;
        font-size: 26rpx;
        color: #fff;
        background-color: #6dd8d9;
        border: 1rpx solid #6dd8d9;
        border-radius: 28rpx;
        transition: all 0.2s;
        
        &:active {
            opacity: 0.8;
            transform: scale(0.96);
        }
        
        &.btn-gray {
            color: #666;
            border-color: #ddd;
        }
    }

    /* 加载更多 */
    .load-more {
        padding: 24rpx 0;
    }

    .no-more {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 32rpx 0;
    }

    .no-more-text {
        margin: 0 24rpx;
        font-size: 26rpx;
        color: #999;
    }

    /* 空状态 */
    .empty-list {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-top: 120rpx;
    }

    .empty-image {
        width: 300rpx;
        height: 300rpx;
        opacity: 0.6;
        margin-bottom: 40rpx;
    }

    .empty-text {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 40rpx;
    }

    .btn-shopping {
        width: 240rpx;
        height: 72rpx;
        line-height: 72rpx;
        background-color: #4cb8d9;
        color: #fff;
        font-size: 28rpx;
        border-radius: 36rpx;
    }
</style>    